package com.sduept.nwld.dataserver.controller.dataview;

import com.sduept.bigdata.fault.system.properties.FaultSystemProperties;
import com.sduept.bigdata.weather.map.MapDataCache;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.model.core.Equipment;
import com.sduept.cim.model.core.Substation;
import com.sduept.cim.model.protection.ProtectionEquipment;
import com.sduept.cim.model.wires.ACLineSegment;
import com.sduept.cim.model.wires.Breaker;
import com.sduept.cim.model.wires.BusbarSection;
import com.sduept.cim.model.wires.PowerTransformer;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.nwld.dataserver.util.LibTreeNode;
import com.sduept.utils.PingYinUtil;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Named
@ViewScoped
public class CimModelController extends AbstractController{
	/**
	 * 
	 */
	private static final long serialVersionUID = 5552779308770511020L;
	@Autowired
	private FaultSystemProperties pros;
	@Autowired
	private CimManager cim;
	@Autowired
	private MapDataCache cimChe;
	private TreeNode root;
	private TreeNode currentSelect;
	
	public static final String TREETYPE = "1";
	private String filterStation;
	
	private String svgContent;
	
	private String selectedSid;
	private String selectedSname;
	
	private String selectFid;
	private String selectFname;
	
	@PostConstruct
	private void init(){
		initTree();
		
	}
	public void refresh(){
		filterStation = "";
		initTree();
	}
	public void initTree(){
		root = new DefaultTreeNode();
		List<Substation> roots = cimChe.getS500List();
		Collections.sort(roots, new Comparator<Substation>(){
			@Override
			public int compare(Substation o1, Substation o2) {
				return PingYinUtil.getPingYin(o1.getName()).compareTo(PingYinUtil.getPingYin(o2.getName()));
			}
		});
		genStationTreeNode(roots);
	}
	public void filterTree(String name){
		root = new DefaultTreeNode();
		List<Substation> roots = cim.getStationByName(name);
		genStationTreeNode(roots);
	}
	private void genStationTreeNode(List<Substation> roots){
		for(Substation sub:roots){
			LibTreeNode subNode  = new LibTreeNode(Substation.class.getSimpleName(),sub,root);
			new LibTreeNode(TREETYPE, new DirNode(sub.getId(),"断路器"), subNode);
			new LibTreeNode(TREETYPE,  new DirNode(sub.getId(),"母线"), subNode);
			new LibTreeNode(TREETYPE,  new DirNode(sub.getId(),"变压器"), subNode);
			new LibTreeNode(TREETYPE,  new DirNode(sub.getId(),"线路"), subNode);
		}
	}
	public TreeNode getTreeNodeResource(){
		return root;
	}
	public void onNodeExpand(NodeExpandEvent event) {
		TreeNode currentNode =  event.getTreeNode();
		if(currentNode.getData() instanceof DirNode){
			DirNode currentObj = (DirNode) currentNode.getData();
			if("线路".equals(currentObj.name)){
				List<ACLineSegment> acs = cim.getAcLineSegmentsBySubstation(currentObj.id);
				for (ACLineSegment bean : acs) {
					 new LibTreeNode(TREETYPE,  bean, currentNode);
				}
			} else if("断路器".equals(currentObj.name)){
				List<Breaker> acs = cim.getBreakersByStationId(currentObj.id);
				for (Breaker bean : acs) {
					 new LibTreeNode(TREETYPE,  bean, currentNode);
				}
			} else if("母线".equals(currentObj.name)){
				List<BusbarSection> acs = cim.getBusbarSectionsByStationId(currentObj.id);
				for (BusbarSection bean : acs) {
					 new LibTreeNode(TREETYPE,  bean, currentNode);
				}
			} else if("变压器".equals(currentObj.name)){
				List<PowerTransformer> acs = cim.getPowerTransformersByStationId(currentObj.id);
				for (PowerTransformer bean : acs) {
					 new LibTreeNode(TREETYPE,  bean, currentNode);
				}
			} 
		} else if(currentNode.getData() instanceof Equipment){
			Equipment project = (Equipment) currentNode.getData();
			List<ProtectionEquipment> beans = cim.getProtectionEquipmentsByProtectedId(project.getId());
			for (ProtectionEquipment b : beans) {
				new DefaultTreeNode(ProtectionEquipment.class.getSimpleName(),b,currentNode);
			}
		} 
	}
	//事件
	public void onNodeSelect(NodeSelectEvent event) {
		currentSelect =  event.getTreeNode();
		if(currentSelect != null){
			if("Substation".equals(currentSelect.getType())){
				Substation sub = (Substation) currentSelect.getData();
				genSvgContent(sub.getId());
				selectedSid = sub.getId();
			} 
		} 
	}
	public void autoCompleteStation(SelectEvent event){
		Object item = event.getObject();
		if(null != item){
			filterTree(item.toString());
		}
	}
	public TreeNode getCurrentSelect() {
		return currentSelect;
	}
	public TreeNode getRoot() {
		return root;
	}
	public void setRoot(TreeNode root) {
		this.root = root;
	}
	public void setCurrentSelect(TreeNode currentSelect) {
		this.currentSelect = currentSelect;
	}
	public class DirNode {
		public String id;
		public String name;
		@Override
		public String toString() {
			return name;
		}
		public DirNode(String id,String name){
			this.id = id;
			this.name = name;
		}
	}

	public String getFilterStation() {
		return filterStation;
	}

	public void setFilterStation(String filterStation) {
		this.filterStation = filterStation;
	}
	
	private void genSvgContent(String stationId){
		StringBuffer sb = new StringBuffer();
		File sf = new File(pros.getSvgBxPath()+stationId+".svg");
		if(sf.exists()){
			RandomAccessFile raf = null;
			try {
				raf = new RandomAccessFile(sf, "r");
				String lstr = raf.readLine();
				boolean startAdd = false;
				while(lstr != null){
					if(startAdd){
						lstr = new String(lstr.trim().getBytes("ISO-8859-1"), "utf-8");
						lstr = lstr.replaceAll("\"", "'");
//						if(lstr.startsWith("<text")){
//							lstr = lstr.replaceFirst("<text", "<text onclick='alert(this)' ");
//						}
						sb.append(lstr);
					} else {
						if(lstr.startsWith("<svg")){
							startAdd = true;
							lstr = new String(lstr.trim().getBytes("ISO-8859-1"), "utf-8");
							lstr = lstr.replaceAll("\"", "'");
							sb.append(lstr);
						}
					}
					lstr = raf.readLine();
				}
				svgContent = sb.toString();
//				log.info(svgContent);
			} catch (Exception e) {
				e.printStackTrace();
			} finally{
				try {
					raf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
	}

	public String getSvgContent() {
		return svgContent;
	}

	public void setSvgContent(String svgContent) {
		this.svgContent = svgContent;
	}

	public String getSelectedSid() {
		return selectedSid;
	}

	public void setSelectedSid(String selectedSid) {
		this.selectedSid = selectedSid;
	}

	public String getSelectFid() {
		return selectFid;
	}

	public void setSelectFid(String selectFid) {
		this.selectFid = selectFid;
	}

	public String getSelectedSname() {
		return selectedSname;
	}

	public void setSelectedSname(String selectedSname) {
		this.selectedSname = selectedSname;
	}

	public String getSelectFname() {
		return selectFname;
	}

	public void setSelectFname(String selectFname) {
		this.selectFname = selectFname;
	}
}
